package com.sxfq.loansupermarket.backsystem.modular.refunds.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.sxfq.loansupermarket.backsystem.common.constant.factory.PageFactory;
import com.sxfq.loansupermarket.backsystem.common.constant.tips.Tip;
import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.exception.BizExceptionEnum;
import com.sxfq.loansupermarket.backsystem.common.exception.BussinessException;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.support.DateTimeKit;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.core.util.CommUtils;
import com.sxfq.loansupermarket.backsystem.core.util.ToolUtil;
import com.sxfq.loansupermarket.backsystem.modular.arrival.entity.CustomerInfo;
import com.sxfq.loansupermarket.backsystem.modular.arrival.service.ICustomerService;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.CheckoutMethodInfo;
import com.sxfq.loansupermarket.backsystem.modular.basicData.entity.PayServiceInfo;
import com.sxfq.loansupermarket.backsystem.modular.refunds.entity.RechargeInfo;
import com.sxfq.loansupermarket.backsystem.modular.refunds.entity.RefundInfo;
import com.sxfq.loansupermarket.backsystem.modular.refunds.entity.SearchRefundInfo;
import com.sxfq.loansupermarket.backsystem.modular.refunds.service.IRefundService;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.ConsultantInfo;
import com.sxfq.loansupermarket.backsystem.modular.tcCenter.entity.PaymentInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 预约客户信息
 *
 * @author py
 * @Date 2018年4月19日23:15:54
 */
@Controller
@RequestMapping("/refund")
public class RefundController extends BaseController {

    @Autowired
    IRefundService service;

    @Autowired
    ICustomerService customerService;

    @Autowired
    private SqlMapper sqlMapper;


    private String PREFIX = "/arrival/customer/";


    @RequestMapping(value = "")
    public String refund(Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return PREFIX + "/customer_refund.html";
    }

    @RequestMapping(value = "/to_refundMethod/{rcoi}")
    public String to_refundMethod(@PathVariable String rcoi, Model model) {
        String reservationsId = rcoi.split(",")[0];
        String customerId = rcoi.split(",")[1];
        String id = rcoi.split(",")[2];
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String tableName = tableHead + "refund_info";
        String sql = "select * from " + tableName + " where id='" + id + "'";
        RefundInfo refundInfo = sqlMapper.selectOne(sql, RefundInfo.class);
        String sql1 = "select t2.customer_name as customerName,t2.reservations_id as reservationsId,t2.medical_record_number as medicalRecordNumber" +
                ",t2.customer_sex as customerSex,t2.arrival_store as outpatientName,t2.customer_age as customerAge,t2.customer_phone as customerPhone ,t2.field_tc as tcName" +
                " from " + this.getTableName() + " t2 where id='" + customerId + "'";
        ConsultantInfo consultantInfo = sqlMapper.selectOne(sql1, ConsultantInfo.class);
        if (consultantInfo != null) {
            if (consultantInfo.getCustomerSex() == 1) {
                consultantInfo.setSex("男");
            } else if (consultantInfo.getCustomerSex() == 2) {
                consultantInfo.setSex("女");
            }else{  consultantInfo.setSex("未知");}
        }
        String deletesql = "delete from temporary_recharge_info where reservations_id='" + reservationsId + "'" +
                " and operation_time='" + refundInfo.getOperationTime() + "'";
        sqlMapper.delete(deletesql);
        model.addAttribute("consultantInfo", consultantInfo);
        model.addAttribute("reservationsId", reservationsId);
        model.addAttribute("customerId", customerId);
        model.addAttribute("operationTime", refundInfo.getOperationTime());
        model.addAttribute("refundInfo", refundInfo);
        model.addAttribute("id", id);
        return PREFIX + "refund_method.html";
    }

    @RequestMapping(value = "/to_choiceRefundMethod/{rci}")
    public String to_choiceRefundMethod(@PathVariable String rci, Model model) {
        String reservationsId = rci.split(",")[0];
        String customerId = rci.split(",")[1];
        String id = rci.split(",")[2];
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ToolUtil.isEmpty(id)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select * from checkout_method_info";
        List<CheckoutMethodInfo> checkoutMethodInfo = sqlMapper.selectList(sql, CheckoutMethodInfo.class);
        model.addAttribute("customerId", customerId);
        model.addAttribute("reservationsId", reservationsId);
        model.addAttribute("id", id);
        model.addAttribute("checkoutMethodInfo", checkoutMethodInfo);
        return PREFIX + "choice_refund_method.html";
    }

    @RequestMapping(value = "/getRefundMethod/{crri}")
    public String getRefundMethod(@PathVariable String crri, Model model) {
        String customerId = crri.split(",")[0];
        String reservationsId = crri.split(",")[1];
        String refundId = crri.split(",")[2];
        String id = crri.split(",")[3];
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String sql = "select * from checkout_method_info where id='" + id + "';";
        CheckoutMethodInfo checkoutMethodInfo = sqlMapper.selectOne(sql, CheckoutMethodInfo.class);
        String tableName = tableHead + "refund_info";
        String sql1 = "select * from " + tableName + " where id='" + refundId + "'";
        RefundInfo refundInfo = sqlMapper.selectOne(sql1, RefundInfo.class);
        model.addAttribute("customerId", customerId);
        model.addAttribute("reservationsId", reservationsId);
        model.addAttribute("refundId", refundId);
        model.addAttribute("id", id);
        model.addAttribute("refundInfo", refundInfo);
        model.addAttribute("checkoutMethodInfo", checkoutMethodInfo);
        return PREFIX + "/getRefundMethods.html";
    }

    @RequestMapping(value = "/refundOut", method = RequestMethod.POST)
    @ResponseBody
    public int refundOut(String customerId, String reservationsId, String recordTime, String operationTime, HttpServletRequest request) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "refund_info";
        String tableName1 = tableHead + "deal_info";
        String tableName2 = tableHead + "recharge_info";
        String selectSql = "select * from " + tableName + " where reservations_id='" + reservationsId + "'" +
                " and customer_id='" + customerId + "' and record_time='" + recordTime + "'";
        RefundInfo refundInfo = sqlMapper.selectOne(selectSql, RefundInfo.class);
        String selectsql1 = "select * from " + this.getTableName() + " where id='" + customerId + "'";
        CustomerInfo customerInfo = sqlMapper.selectOne(selectsql1, CustomerInfo.class);
        String updateSql = "";
        if (refundInfo.getRefundsType() == 2) {
            updateSql = "update " + this.getTableName() + " set actual_account_balance=actual_account_balance-'" + refundInfo.getRefundMoney() + "'" +
                    " ,account_arrears=account_arrears+" + refundInfo.getRefundMoney() + " where reservations_id='" + reservationsId + "'";
        } else if (refundInfo.getRefundsType() == 1) {
            updateSql = "update " + this.getTableName() + " set actual_account_balance=actual_account_balance-'" + refundInfo.getRefundMoney() + "'" +
                    "  where reservations_id='" + reservationsId + "'";
        } else {
            updateSql = "update " + this.getTableName() + " set actual_account_balance=actual_account_balance-'" + refundInfo.getRefundMoney() + "'" +
                    "  where reservations_id='" + reservationsId + "'";
        }
        if (operationTime == null || operationTime == "") {
            String isql1 = "INSERT INTO `reservations_aggregate_info` ( `reservations_id`,`arrival_store`,`customer_id`,`tc_name`,`doctor`,`money`,  `get_time`) VALUES " +
                    " ( '" + reservationsId + "','" + ShiroKit.getUser().getOutpatientName() + "','" + customerId + "','" + customerInfo.getFieldTc() + "','" + customerInfo.getDoctor() + "', -" + refundInfo.getRefundMoney() + ", '" + DateTimeKit.now() + "');";
            sqlMapper.insert(isql1);
            sqlMapper.update(updateSql);
        } else {
            String sumSql = "select sum(folding_pay) as foldingPay  from " + tableName1 + " where reservations_id='" + reservationsId + "'" +
                    " and operation_time='" + operationTime + "';";
            PaymentInfo paymentInfo = sqlMapper.selectOne(sumSql, PaymentInfo.class);
            Double sp = 0.00;
            if (paymentInfo.getFoldingPay() == 0) {
                sp = 0.00;
            } else {
                sp = refundInfo.getRefundMoney() / paymentInfo.getFoldingPay();
            }
            String id = CommUtils.getUUID();
            String time = DateTimeKit.now();
            id=(id+time).substring(10,40);
            if (refundInfo.getRefundsType() == 2) {
                String selectupdatesql="select sum(service_actual_pay) as serviceActualPay from " + tableName1 + " where reservations_id='" + reservationsId + "' and operation_time='" + operationTime + "' and deal_status!='不做了' limit 0,1";
                PayServiceInfo info=sqlMapper.selectOne(selectupdatesql,PayServiceInfo.class);
                Double serviceActualPay=info.getServiceActualPay()- refundInfo.getRefundMoney();
                String insertSql = "insert into " + tableName1 + " " +
                        "(id,customer_id,reservations_id,pay_service_id,tc_name,pay_service_num,service_actual_pay,remarks,deal_status,operation_time,get_time,outpatient_name,folding_pay,pay_service,left_up,left_down,right_up,right_down,doctor,arrears) " +
                        "select '"+id+"',customer_id,reservations_id,pay_service_id,tc_name,pay_service_num,-" + refundInfo.getRefundMoney() + ",remarks,'继续做','" + operationTime + "','" + time + "','" + ShiroKit.getSessionAttr("outpatientName") +
                        "',sum(folding_pay),pay_service,left_up,left_down,right_up,right_down,doctor,sum(folding_pay)-"+serviceActualPay+" from " + tableName1 + " where reservations_id='" + reservationsId + "' and operation_time='" + operationTime + "' and operation_time=get_time limit 0,1";
                sqlMapper.insert(insertSql);
            } else if (refundInfo.getRefundsType() == 1) {
                String selectupdatesql="select sum(service_actual_pay) as serviceActualPay from " + tableName1 + " where reservations_id='" + reservationsId + "' and operation_time='" + operationTime + "' and deal_status!='不做了' limit 0,1";
                PayServiceInfo info=sqlMapper.selectOne(selectupdatesql,PayServiceInfo.class);
                Double serviceActualPay=info.getServiceActualPay();
                String insertSql = "insert into " + tableName1 + " " +
                        "(id,customer_id,reservations_id,pay_service_id,tc_name,pay_service_num,service_actual_pay,remarks,deal_status,operation_time,get_time,outpatient_name,folding_pay,pay_service,left_up,left_down,right_up,right_down,doctor,arrears) " +
                        "select '"+id+"',customer_id,reservations_id,pay_service_id,tc_name,pay_service_num,-" + refundInfo.getRefundMoney() + ",remarks,'不做了','" + operationTime + "','" + time + "','" + ShiroKit.getSessionAttr("outpatientName") +
                        "',sum(folding_pay),pay_service,left_up,left_down,right_up,right_down,doctor,sum(folding_pay)-"+serviceActualPay+" from " + tableName1 + " where customer_id='" + customerId + "' and operation_time='" + operationTime + "' and operation_time=get_time limit 0,1";
                sqlMapper.insert(insertSql);
            }
            String sumSql2 = "select b.id,b.service_actual_pay as serviceActualPay, c.department as department from " + tableName1 + " b " +
                    "left join pay_service_info c on b.pay_service_id=c.id  where reservations_id='" + reservationsId + "' " +
                    "and operation_time='" + operationTime + "'";
            List<RechargeInfo> rechargeInfoList = sqlMapper.selectList(sumSql2, RechargeInfo.class);
            for (int i = 0; i < rechargeInfoList.size(); i++) {
                Double money = 0.00;
                if (rechargeInfoList.size() > 0) {
                    money = refundInfo.getRefundMoney() / rechargeInfoList.size();
                } else {
                    money = 0.00;
                }
                String isql1 = "INSERT INTO `reservations_aggregate_info` ( `reservations_id`,`arrival_store`,`customer_id`,`tc_name`,`doctor`,`money`,`department`,  `get_time`) VALUES " +
                        " ( '" + reservationsId + "','" + ShiroKit.getUser().getOutpatientName() + "','" + customerId + "','" + customerInfo.getFieldTc() + "','" + customerInfo.getDoctor() + "', -" + money + ", '" + rechargeInfoList.get(i).getDepartment() + "', '" + DateTimeKit.now() + "');";
                sqlMapper.insert(isql1);
            }
            sqlMapper.update(updateSql);
        }
        String isql = "INSERT INTO `aggregate_info` ( `reservations_id`, `arrival_store`,`customer_id`, `money`, `get_time`) VALUES\n" +
                " ( '" + reservationsId + "', '" + ShiroKit.getUser().getOutpatientName() + "','" + customerId + "', -" + refundInfo.getRefundMoney() + ", '" + DateTimeKit.now() + "');";
        sqlMapper.insert(isql);
        String sql2 = " select max(document_number) as documentNumber from " + tableName + " ";
        String sql1 = " select max(document_number) as documentNumber from " + tableName2 + " ";
        RechargeInfo rechargeInfo1 = sqlMapper.selectOne(sql1, RechargeInfo.class);
        RefundInfo refundInfo1 = sqlMapper.selectOne(sql2, RefundInfo.class);
        Double documentNumbers1 = Double.parseDouble(rechargeInfo1.getDocumentNumber());
        Double documentNumbers2 = Double.parseDouble(refundInfo1.getDocumentNumber());
        Double documentNumbers=0.00;
        if(documentNumbers1>documentNumbers2){
            documentNumbers=documentNumbers1;
        }else{
            documentNumbers=documentNumbers2;
        }
        documentNumbers = documentNumbers + 1;
        String documentNumber = "";
        if (documentNumbers < 10) {
            documentNumber = "000000" + documentNumbers;
        } else if (documentNumbers >= 10 && documentNumbers < 100) {
            documentNumber = "00000" + documentNumbers;
        } else if (documentNumbers >= 100 && documentNumbers < 1000) {
            documentNumber = "0000" + documentNumbers;
        } else if (documentNumbers >= 1000 && documentNumbers < 10000) {
            documentNumber = "000" + documentNumbers;
        } else if (documentNumbers >= 10000 && documentNumbers < 100000) {
            documentNumber = "00" + documentNumbers;
        } else if (documentNumbers >= 100000 && documentNumbers < 1000000) {
            documentNumber = "0" + documentNumbers;
        } else if (documentNumbers >= 1000000) {
            documentNumber = "" + documentNumbers;
        }
        documentNumber=documentNumber.substring(0,documentNumber.length()-2);
        String sql = "INSERT INTO " + tableName + " (`id`,refunds_type,`customer_id`,`reservations_id`,  `record_people`,checkout_method," +
                " `refund_money`, refund_time,`record_time`,remarks,is_refund,refund_people,operation_time,document_number)  " +
                " select right(CONCAT(id,record_time),40) , `status`, `customer_id`, `reservations_id`, " +
                " `recharge_people`, `checkout_method`, " +
                "  `actual_account_balance`, `recharge_time`, `record_time`, " +
                " `remarks`,'是','" + ShiroKit.getUser().getAccount() + "',operation_time,'"+documentNumber+"' from temporary_recharge_info where reservations_id='" + reservationsId + "'" +
                " and customer_id='" + customerId + "' and record_time='" + recordTime + "'";
        String deletesql = "delete from temporary_recharge_info where reservations_id='" + reservationsId + "'" +
                " and customer_id='" + customerId + "' and record_time='" + recordTime + "'";
        String deletesql1 = "delete from " + tableName + " where reservations_id='" + reservationsId + "'" +
                " and customer_id='" + customerId + "' and record_time='" + recordTime + "'";
        sqlMapper.delete(deletesql1);
        sqlMapper.insert(sql);
        return sqlMapper.delete(deletesql);
    }

    @RequestMapping(value = "/getChangeRefund", method = RequestMethod.POST)
    @ResponseBody
    public int getChangeRefund(String id, String customerId, String reservationsId, String operationTime, HttpServletRequest request) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "refund_info";
        String tableName1 = tableHead + "deal_info";
        String sql = "update " + tableName + " set is_refund='是',refund_time='" + DateTimeKit.now() + "',refund_people='" + ShiroKit.getUser().getAccount() + "' where id='" + id + "'";
        String selectSql = "select * from " + tableName + " where id='" + id + "'";
        RefundInfo refundInfo = sqlMapper.selectOne(selectSql, RefundInfo.class);
        String updateSql = "";
        if (refundInfo.getRefundsType() == 2) {
            updateSql = "update " + this.getTableName() + " set actual_account_balance=actual_account_balance-'" + refundInfo.getRefundMoney() + "'" +
                    " ,account_arrears=account_arrears+" + refundInfo.getRefundMoney() + " where reservations_id='" + reservationsId + "'";
        } else if (refundInfo.getRefundsType() == 1) {
            updateSql = "update " + this.getTableName() + " set actual_account_balance=actual_account_balance-'" + refundInfo.getRefundMoney() + "'" +
                    "  where reservations_id='" + reservationsId + "'";
        } else {
            updateSql = "update " + this.getTableName() + " set actual_account_balance=actual_account_balance-'" + refundInfo.getRefundMoney() + "'" +
                    "  where reservations_id='" + reservationsId + "'";
        }
        if (operationTime == null || operationTime == "") {
            sqlMapper.update(updateSql);
            return sqlMapper.update(sql);
        } else {
            String sumSql = "select sum(folding_pay) as foldingPay  from " + tableName1 + " where reservations_id='" + reservationsId + "'" +
                    " and operation_time='" + operationTime + "';";
            PaymentInfo paymentInfo = sqlMapper.selectOne(sumSql, PaymentInfo.class);
            String updatesql2 = "";
            Double sp = 0.00;
            if (paymentInfo.getFoldingPay() == 0) {
                sp = 0.00;
            } else {
                sp = refundInfo.getRefundMoney() / paymentInfo.getFoldingPay();
            }
            if (refundInfo.getRefundsType() == 2) {
                updatesql2 = " update " + tableName1 + " set service_actual_pay=service_actual_pay" +
                        "-folding_pay*" + sp + "" +
                        ", arrears=arrears+folding_pay*" + sp + " where reservations_id='" + reservationsId + "'" +
                        " and operation_time='" + operationTime + "';";
            } else if (refundInfo.getRefundsType() == 1) {
                updatesql2 = " update " + tableName1 + " set service_actual_pay=service_actual_pay" +
                        "-folding_pay*" + sp + "" +
                        " where reservations_id='" + reservationsId + "'" +
                        " and operation_time='" + operationTime + "';";
            }
            String isql = "INSERT INTO `aggregate_info` ( `reservations_id`, `arrival_store`,`customer_id`, `money`, `get_time`) VALUES\n" +
                    " ( '" + reservationsId + "', '" + ShiroKit.getUser().getOutpatientName() + "','" + customerId + "', -" + refundInfo.getRefundMoney() + ", '" + DateTimeKit.now() + "');";
            String sumSql2 = "select b.id,b.service_actual_pay as serviceActualPay, c.department as department from " + tableName1 + " b " +
                    "left join pay_service_info c on b.pay_service_id=c.id  where reservations_id='" + reservationsId + "' " +
                    "and operation_time='" + operationTime + "'";
            List<RechargeInfo> rechargeInfoList = sqlMapper.selectList(sumSql2, RechargeInfo.class);
            String selectsql1 = "select * from " + this.getTableName() + " where id='" + customerId + "'";
            CustomerInfo customerInfo = sqlMapper.selectOne(selectsql1, CustomerInfo.class);
            for (int i = 0; i < rechargeInfoList.size(); i++) {
                String isql1 = "INSERT INTO `reservations_aggregate_info` ( `reservations_id`,`arrival_store`,`customer_id`,`tc_name`,`doctor`,`money`,`department`,  `get_time`) VALUES " +
                        " ( '" + reservationsId + "','" + ShiroKit.getUser().getOutpatientName() + "','" + customerId + "','" + customerInfo.getFieldTc() + "','" + customerInfo.getDoctor() + "', -" + refundInfo.getRefundMoney() + ", '" + rechargeInfoList.get(i).getDepartment() + "', '" + DateTimeKit.now() + "');";
                sqlMapper.insert(isql1);
            }
            sqlMapper.insert(isql);
            sqlMapper.update(updatesql2);
            sqlMapper.update(updateSql);
            return sqlMapper.update(sql);
        }
    }


    @RequestMapping(value = "/addBalances", method = RequestMethod.POST)
    @ResponseBody
    public int addBalances(String customerId, String reservationsId, Double amountOfBalance, String refundId, String checkoutMethod, String remarks, HttpServletRequest request) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String id = CommUtils.getUUID();
        Random rand = new Random();
        int randomNumber = rand.nextInt(999999);
        id = id + randomNumber;
        String tableName = tableHead + "refund_info";
        String sql1 = "select * from " + tableName + " where id='" + refundId + "'";
        RefundInfo refundInfo = sqlMapper.selectOne(sql1, RefundInfo.class);
        String operationTime = "";
        if (refundInfo != null) {
            if (refundInfo.getOperationTime() == null || refundInfo.getOperationTime() == "") {
                operationTime = "null";
            } else {
                operationTime = "'" + refundInfo.getOperationTime() + "'";
            }
        } else {
            operationTime = "null";
        }
        String sql = " INSERT INTO `temporary_recharge_info` (`id`, `status`, `customer_id`, `reservations_id`, " +
                "  `recharge_people`, `checkout_method`, " +
                " `actual_account_balance`, `recharge_time`, " +
                "  `remarks`,record_time ,operation_time) VALUES " +
                "('" + id + "', 2, '" + customerId + "', '" + reservationsId + "', " +
                "  '" + ShiroKit.getUser().getAccount() + "', '" + checkoutMethod + "', " +
                " " + amountOfBalance + ", '" + DateTimeKit.now() + "'," +
                " '" + remarks + "','" + refundInfo.getRecordTime() + "'," + operationTime + ");";
        return sqlMapper.insert(sql);
    }

    @RequestMapping(value = "/closesBalance", method = RequestMethod.POST)
    @ResponseBody
    public int closesBalance(String customerId, String reservationsId, String operationTime, HttpServletRequest request) {
        String deletesql = "delete from temporary_recharge_info where reservations_id='" + reservationsId + "'" +
                " and operation_time='" + operationTime + "'";
        return sqlMapper.delete(deletesql);
    }

    /**
     *
     */
    @RequestMapping("/refundList")
    @ResponseBody
    public Object refundList(SearchRefundInfo info, HttpServletRequest request) {
        Page<RefundInfo> page = new PageFactory<RefundInfo>().defaultPage();
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        try {
            List<RefundInfo> list = new ArrayList<RefundInfo>();
            list = service.selectPageListRefundInfo(page, info);
            if (list.size() == 0) {
                page.setCurrent(1);
                list = service.selectPageListRefundInfo(page, info);
            }
            page.setRecords(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.packForBT(page);
    }


    @RequestMapping(value = "/refund")
    @ResponseBody
    public int refund(@Valid CustomerInfo info, BindingResult result) throws Exception {
        if (result.hasErrors()) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String sql1 = "select sum(actual_account_balance) as actualAccountBalance from " + this.getTableName() + " where reservations_id='" + info.getReservationsId() + "'";
//        String sql1 = "select sum(actual_account_balance) as actualAccountBalance from " + this.getTableName() + " where id='" + info.getId() + "'";
        CustomerInfo customerInfo = sqlMapper.selectOne(sql1, CustomerInfo.class);
        if (info.getRefundMoney() > customerInfo.getActualAccountBalance()) {
            return 0;
        } else {
            String id = CommUtils.getUUID();
            Random rand = new Random();
            int randomNumber = rand.nextInt(999999);
            id = id + randomNumber;
            String tableHead = ShiroKit.getUser().getAbbreviation();
            String tableName = tableHead + "refund_info";
            String sql = "INSERT INTO " + tableName + " (`id`,`customer_id`,`reservations_id`,  `record_people`, `refund_money`, `record_time`) VALUES" +
                    "('" + id + "','" + info.getId() + "','" + info.getReservationsId() + "','" + ShiroKit.getUser().getAccount() + "" +
                    "','" + info.getRefundMoney() + "','" + DateTimeKit.now() + "');";
            sqlMapper.insert(sql);
            return 1;
        }
    }

    @RequestMapping(value = "/addRefund", method = RequestMethod.POST)
    @ResponseBody
    public int addRefund(String customerId, String reservationsId, String operationTime, Double refundMoney, Double refundsType, String remarks, HttpServletRequest request) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "refund_info";
        String id = CommUtils.getUUID();
        Random rand = new Random();
        int randomNumber = rand.nextInt(999999);
        id = id + randomNumber;
        String sql = "INSERT INTO " + tableName + " (`id`,`customer_id`,`reservations_id`,  `record_people`, `refund_money`, `record_time`, `operation_time`, `remarks`, `refunds_type`) VALUES" +
                "('" + id + "','" + customerId + "','" + reservationsId + "','" + ShiroKit.getUser().getAccount() + "" +
                "','" + refundMoney + "','" + DateTimeKit.now() + "','" + operationTime + "','" + remarks + "'," + refundsType + ");";
        return sqlMapper.insert(sql);
    }

    @RequestMapping(value = "/addSpecialRefund", method = RequestMethod.POST)
    @ResponseBody
    public int addSpecialRefund(String customerId, String reservationsId, Double refundsType, Double refundMoney, String remarks, HttpServletRequest request) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "refund_info";
        String id = CommUtils.getUUID();
        Random rand = new Random();
        int randomNumber = rand.nextInt(999999);
        id = id + randomNumber;
        String sql = "INSERT INTO " + tableName + " (`id`,`customer_id`,`reservations_id`,  `record_people`, `refund_money`, `record_time`,  `remarks`, `refunds_type`) VALUES" +
                "('" + id + "','" + customerId + "','" + reservationsId + "','" + ShiroKit.getUser().getAccount() + "" +
                "','" + refundMoney + "','" + DateTimeKit.now() + "', '" + remarks + "', " + refundsType + ");";
        return sqlMapper.insert(sql);
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete/{id}")
    @ResponseBody
    public Tip delete(@PathVariable String id) throws Exception {
        service.delete(id);
        return SUCCESS_TIP;
    }


    @RequestMapping(value = "/to_recharge/{customerId}")
    public String to_recharge(@PathVariable String customerId, Model model) {
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        CustomerInfo customerInfo = customerService.selectOneById(customerId);
        model.addAttribute("customerId", customerId);
        model.addAttribute("reservationsId", customerInfo.getReservationsId());
        return PREFIX + "recharge.html";
    }

    @RequestMapping(value = "/to_specialRefund/{rc}")
    public String to_specialRefund(@PathVariable String rc, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String reservationsId = rc.split(",")[0];
        String customerId = rc.split(",")[1];
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        model.addAttribute("customerId", customerId);
        model.addAttribute("reservationsId", reservationsId);
        return PREFIX + "special_refund.html";
    }

    @RequestMapping(value = "/to_refund/{cro}")
    public String to_refund(@PathVariable String cro, Model model) {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String customerId = cro.split(",")[0];
        String reservationsId = cro.split(",")[1];
        String operationTime = cro.split(",")[2];
        if (ToolUtil.isEmpty(customerId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ToolUtil.isEmpty(reservationsId)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (ToolUtil.isEmpty(operationTime)) {
            throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        String tableName1 = tableHead + "deal_info";
        String sql = "select t1.id as id,t1.customer_id as customerId ,t1.reservations_id as reservationsId ,t1.outpatient_name as outpatientName , t1.deal_status  as dealStatus, t1.tc_name as tcName ,t1.pay_service_num as payServiceNum ," +
                " t1.service_actual_pay as serviceActualPay ,left(t1.operation_time,19) as operationTime,t1.remarks as remarks," +
                " t1.folding_pay as foldingPay,t1.to_void_cause as toVoidCause,t1.pay_service as payService,t1.arrears as arrears," +
                "t2.id as payServiceId,t2.department as department,t2.first_level_project as firstLevelProject," +
                "t2.pay_service_name as payServiceName, t2.pay_service_price_one as payServicePriceOne, t2.pay_service_price_two as payServicePriceTwo," +
                "t1.to_void_cause as toVoidCause ,t1.no_deal_cause as noDealCause from " + tableName1 + " t1 left join pay_service_info t2 on t1.pay_service_id=t2.id " +
                " where t1.deal_status='已成交' and  t1.operation_time='" + operationTime + "' and t1.reservations_id='" + reservationsId + "'";
        List<PayServiceInfo> openBillList = sqlMapper.selectList(sql, PayServiceInfo.class);
        Double totleReceivable = 0.00;
        Double totleFoldingPay = 0.00;
        Double totleServiceActualPay = 0.00;
        Double accountArrears = 0.00;
        for (PayServiceInfo info : openBillList) {
            if (info.getPayServiceId() != null && info.getPayServiceId() != "") {
                totleReceivable += (info.getPayServicePriceTwo()) * (info.getPayServiceNum());
                totleFoldingPay += info.getFoldingPay();
                totleServiceActualPay += info.getServiceActualPay();
                accountArrears += info.getArrears();
                info.setTotleReceivable(totleReceivable);
                info.setTotleFoldingPay(totleFoldingPay);
                info.setTotleServiceActualPay(totleServiceActualPay);
                info.setAccountArrears(accountArrears);
            }
        }
        model.addAttribute("customerId", customerId);
        model.addAttribute("reservationsId", reservationsId);
        model.addAttribute("operationTime", operationTime);
        model.addAttribute("totleFoldingPay", totleFoldingPay);
        model.addAttribute("totleServiceActualPay", totleServiceActualPay);
        model.addAttribute("openBillList", openBillList);
        return PREFIX + "refund.html";
    }


    public String getTableName() {
        String tableHead = ShiroKit.getUser().getAbbreviation();
        String tableName = tableHead + "customer_info";
        if (tableHead == "" || tableHead == null) {
            LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
            ShiroKit.getSubject().logout();
            return "/login.html";
        }
        return tableName;
    }
}
